using System.Linq;
using System.Collections.Generic;
using Managistics.Model;
using NHibernate.Criterion;
using NHibernate;
using System;
using Managistics.Model.ValueObject;
using Managistics.Utility;

namespace Managistics.Core.Repositories.Impl
{
    public class PurchaseOrderRepository : RepositoryBase<PurchaseOrder, string>, IPurchaseOrderRepository
    {
        public List<PurchaseOrder> GetPurchaseOrder(PurchaseOrderVO param)
        {
            var query = this.Session.QueryOver<PurchaseOrder>();
            if (StringUtils.hasData(param.Id))
            {
                query.Where(x => x.Orderid.IsLike(param.Id, MatchMode.Anywhere));
            }

            if (StringUtils.hasData(param.SupplierName))
            {
                Supplier supplierReference = null;
                query.JoinAlias(x => x.Supplier, () => supplierReference);         
                query.Where(x => supplierReference.Name.IsLike(param.SupplierName, MatchMode.Anywhere));
            }

            if (StringUtils.hasData(param.GoodCode) || StringUtils.hasData(param.GoodName))
            {
                PurchaseOrderDetail purchaseOrderDetail = null;
                query.JoinAlias(x => x.PurchaseOrderDetail, () => purchaseOrderDetail);
                if (StringUtils.hasData(param.GoodCode))
                {
                    query.Where(x => purchaseOrderDetail.ItemId.IsLike(param.GoodCode, MatchMode.Anywhere));
                }

                if (StringUtils.hasData(param.GoodName))
                {
                    Good good = null;
                    query.JoinAlias(x => purchaseOrderDetail.Good, () => good);
                    query.Where(x => good.Name.IsLike(param.GoodName, MatchMode.Anywhere));
                }               
            }


            query.Where(x => x.Orderdate >= DateUtils.string2DateTime(param.StartDate)
                    && x.Orderdate <= (DateUtils.string2DateTime(param.EndDate)));
            
            return query.List().ToList<PurchaseOrder>();
                        
        }
    }
}